package rest.service;

import org.springframework.stereotype.Service;
import rest.Config;

import java.io.*;
import java.time.LocalDateTime;

/**
 * Created by liuzesen on 16/1/15.
 */

@Service
public class RunService
{
    public String runScript()
    {
        Config config = Config.getInstance();
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime preDateTime = localDateTime.minusSeconds(config.getTimeInterval() + 1);
        LocalDateTime nextDateTime;
        File file = new File(config.getFilePath());

        // 读取时间，控制并发
        try
        {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = "";
            line = reader.readLine();
            if (line != "" && line != null)
                preDateTime = LocalDateTime.parse(line);
            fileInputStream.close();
            inputStreamReader.close();
            reader.close();
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        nextDateTime = preDateTime.plusSeconds(config.getTimeInterval());
        if (localDateTime.isBefore(nextDateTime))
        {
            return "rebuilding now, next rebuild is available after " + nextDateTime.toString();
        }

        // 运行脚本
        synchronized (file)
        {
            try
            {
                String scriptPath = config.getScriptPath();
                Process process = Runtime.getRuntime().exec(scriptPath);
                process.waitFor();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null)
                {
                    stringBuilder.append(line).append("\n");
                }

                // 执行成功，记录下次运行时间
                nextDateTime = LocalDateTime.now().plusSeconds(config.getTimeInterval());
                FileWriter fw = new FileWriter(config.getFilePath());
                fw.write(nextDateTime.toString());
                fw.close();

                return stringBuilder.toString(); // 返回脚本输出语句
            } catch (Exception e)
            {
                e.printStackTrace();
                return e.getMessage();
            }
        }
    }
}
